package com.shiguiwu.springmybatis.spring.aop.proxy;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aop.AfterAdvice;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: 代理
 * @author: stone
 * @date: Created by 2021/3/15 9:53
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springmybatis.spring.aop.proxy
 */
public class ProxyTests {

    public static void main(String[] args) {
//        test();
//        testPlus((proxy, method, arg) -> {
//            System.out.println("我是InvocationHandler r，被调用的方法是：" + method.getName());
//            return null;
//        });

        IService proxy = UseTimeInvocationHandler.createProxy(new ServiceA(), IService.class);
        proxy.m1();
        proxy.m2();
        proxy.m3();

        //扩展到任务方法
        UserService service = UseTimeInvocationHandler.createProxy(new UserServiceImpl(), UserService.class);
        int tom = service.insert("tom");
        System.out.println(tom);
    }


    /**
     * 1.使用InvocationHandler接口创建代理类的处理器
     * 2.使用Proxy类的静态方法newProxyInstance直接创建代理对象
     * 3.使用代理对象
     */
    public static void test() {
        // 1. 创建代理类的处理器
        InvocationHandler invocationHandler = (proxy, method, args) -> {
            System.out.println("我是InvocationHandler，被调用的方法是：" + method.getName());
            return null;
        };
        // 2. 创建代理实例
        IService proxyService = (IService) Proxy.newProxyInstance(IService.class.getClassLoader(), new Class[]{IService.class}, invocationHandler);
        // 3. 调用代理的方法
        proxyService.m1();
        proxyService.m2();
        proxyService.m3();
    }

    public static void testPlus(InvocationHandler invocationHandler) {
        // 1. 创建代理类的处理器
        // 2. 创建代理实例
        IService proxyService = (IService) Proxy.newProxyInstance(IService.class.getClassLoader(), new Class[]{IService.class}, invocationHandler);
        // 3. 调用代理的方法
        proxyService.m1();
        proxyService.m2();
        proxyService.m3();
    }
}

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

